package utils

import (
	"fmt"
	"strconv"
	"strings"
)

func FormatNum(num float64) string {
	var (
		unit     = "元"
		append   = "人民币"
		accuracy = 2
	)
	if num/100000000 >= 1 {
		res := num / 100000000
		return strconv.FormatFloat(res, 'f', accuracy, 64) + "兆" + unit + append
	}
	if num/10000 >= 1 {
		res := num / 10000
		return strconv.FormatFloat(res, 'f', accuracy, 64) + "亿" + unit + append
	} else {
		return strconv.FormatFloat(num, 'f', accuracy, 64) + "万" + unit + append
	}
}

func ConvertNumToCap(num float64) string {
	strnum := strconv.FormatFloat(num, 'f', 2, 64)
	capitalSlice := []string{"万", "亿", "兆"}
	index := 0
	result := ""
	sdivision := strings.Split(strnum, ".")
	sl := sdivision[0]
	if len(sdivision) > 1 {
		result = "." + sdivision[1]
	}
	for len(sl) > 4 {
		result = capitalSlice[index] + sl[len(sl)-4:] + result
		index = index + 1
		sl = sl[0 : len(sl)-4]
	}
	result = sl + result
	result = strings.Replace(result, "万0000", "万", -1)
	result = strings.Replace(result, "亿0000", "亿", -1)
	result = strings.Replace(result, "兆0000", "兆", -1)
	result = strings.Replace(result, "亿万", "亿", -1)
	result = strings.Replace(result, "兆亿", "兆", -1)
	return result
}

func EncryMobile(mobile string) string {
	if len(mobile) <= 7 {
		return mobile
	}
	return fmt.Sprintf("%s****%s", mobile[:3], mobile[7:])
}

func ReplaceSqlStr(str string) string {
	str = strings.ReplaceAll(str, "'", "''")
	str = strings.ReplaceAll(str, "\\", "\\\\\\\\")
	str = strings.ReplaceAll(str, "%", "\\%")
	str = strings.ReplaceAll(str, "_", "\\_")
	return str
}

/*
*

	保留4位小数点
*/
func Decimal(str string) (float64, error) {
	f, err := strconv.ParseFloat(str, 64)
	if err != nil {
		return 0, err
	}

	f1, errF := strconv.ParseFloat(fmt.Sprintf("%.4f", f), 64)
	if errF != nil {
		return 0, err
	}
	return f1, nil
}
